package servlet;

import bean.Activity;
import bean.ActivityUser;
import bean.PageBean;
import dao.ActivityDao;
import dao.ActivityUserDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import util.DateUtil;
import util.JsonWrapper;
import util.ResponseUtil;
import util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * Created by rookie on 2017/10/25.
 */
public class ActivityUserServlet extends HttpServlet {
    private ActivityUserDao activityUserDao = new ActivityUserDao();
    private ActivityDao activityDao = new ActivityDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        JsonWrapper result = new JsonWrapper();
        String startStr = req.getParameter("start");  //当前页
        String pagesizeStr = req.getParameter("pagesize");  //页记录数
        String userId = req.getParameter("userId");

        PageBean pageBean;
        if (null != startStr && null != pagesizeStr) {
//			分页查询
            int start = 0;
            int pagesize = 0;

            if (!StringUtil.isEmpty(startStr)) {
                start = Integer.parseInt(startStr);
            }
            if (!StringUtil.isEmpty(pagesizeStr)) {
                pagesize = Integer.parseInt(pagesizeStr);
            }
            pageBean = new PageBean(start, pagesize);
        } else {
            pageBean = null;
        }

        List<Object> activityList = null;  //查询返回的活动信息
        JSONArray jsonArray = new JSONArray();
        try {
            activityList = activityUserDao.getActivityList(pageBean, userId, null, null);
            if (activityList.size() != 0) {
                result.setStatus(200);
                result.setMsg("success");
            } else {
                result.setStatus(200);
                result.setMsg("No record!");
            }

            for (Object single : activityList) {
                JSONObject jsonObject = JsonWrapper.parseFromObject(single);
                jsonArray.add(jsonObject);
            }

            //System.out.println(resultActivityUser.size());
            result.setDataEntry("total", activityList.size());

            result.setDataJsonArray("values", jsonArray);
        } catch (Exception e) {
            //查询失败
            result.setStatus(401);
            result.setMsg("query failed");
            e.printStackTrace();
        } finally {
            System.out.println(result.get());
        }
        ResponseUtil.write(resp, result.get());
    }

    /**
     * 退出活动
     */
    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String userId = req.getParameter("userId");
        String activityId = req.getParameter("activityId");
        if (userId == null || activityId == null) {
            ResponseUtil.writeBadRequest(resp);
            return;
        }
        ActivityUser activityUser = new ActivityUser();
        activityUser.setUserId(userId);
        activityUser.setActivityId(activityId);

        List<Object> resultActivityUser;  //查询返回的用户信息
        List<Object> resultActivity;  //查询返回的用户信息

        JsonWrapper result = new JsonWrapper();
        try {

            //活动的现有人数 - 1
            resultActivity = activityDao.activityList(null, new Activity(activityId), null, null, null, null, null, null);
            Activity tempActivity = (Activity) resultActivity.get(0);
            String replyTime = tempActivity.getReplyTime();
            String startTime = tempActivity.getStartTime();
            Date replyTime1 = DateUtil.parse(replyTime);
            Date startTime1 = DateUtil.parse(startTime);
            String now1 = DateUtil.nowTime();
            String now2 = DateUtil.parseTime(now1);
            Date time = DateUtil.parse(now2);
            boolean rightTime = time.getTime() >= replyTime1.getTime() && time.getTime() <= startTime1.getTime();

            int tempCount = Integer.parseInt(tempActivity.getTempCount()) - 1;
            tempActivity.setTempCount(String.valueOf(tempCount));
            //更新活动
            int modifyNum = activityDao.activityModify(tempActivity);
            //找到活动用户表的id
            resultActivityUser = activityUserDao.activityUserList(null, activityUser, null, null);
            ActivityUser tempActivityUser = (ActivityUser) resultActivityUser.get(0);
            String activityUserId = tempActivityUser.getActivityUserId();
            //更新活动用户表
            int delNum = activityUserDao.activityUserDelete(activityUserId);
            if (delNum == 1 && modifyNum == 1 && rightTime) {
                result.setStatus(200);  //删除成功
                result.setMsg("success");
                result.setDataEntry("total", 1);
            } else {
                result.setStatus(400);  //删除失败
                result.setMsg("数据库更新失败或活动已开始，不可退出");
            }
        } catch (Exception e) {
            result.setStatus(401);  //删除失败
            result.setMsg("failed");
            e.printStackTrace();
        } finally {
            System.out.println(result);
        }
        ResponseUtil.write(resp, result.get());
    }

    /**
     * 增加
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        List<Object> resultActivity;  //查询返回的用户信息
        List<Object> resultActivityUser;  //查询返回的用户信息

        String userId = req.getParameter("userId");
        String activityId = req.getParameter("activityId");

        ActivityUser activityUser = new ActivityUser();
        activityUser.setUserId(userId);
        activityUser.setActivityId(activityId);

        JsonWrapper result = new JsonWrapper();

        try {
            //判断该用户是否已经参加该活动
            resultActivityUser = activityUserDao.activityUserList(null, activityUser, null, null);
            if (resultActivityUser.size() > 0) {
                result.setStatus(100);  //
                result.setMsg("您已参加该活动");
            } else {
                //获取要参加的活动
                resultActivity = activityDao.activityList(null, new Activity(activityId), null, null, null, null, null, null);
                Activity tempActivity = (Activity) resultActivity.get(0);
                int maxCount = Integer.parseInt(tempActivity.getMaxUserCount());
                int tempCount = Integer.parseInt(tempActivity.getTempCount());
                int status = Integer.parseInt(tempActivity.getStatus());
                System.out.println("status:" + status);
                String startTime = tempActivity.getReplyTime();
                Date time1 = DateUtil.parse(startTime);
                System.out.println("开始时间：" + time1);
                String endTime = tempActivity.getStartTime();
                Date time2 = DateUtil.parse(endTime);
                System.out.println("结束时间：" + time2);
                String now1 = DateUtil.nowTime();
                String now2 = DateUtil.parseTime(now1);
                Date time = DateUtil.parse(now2);
                System.out.println("时间:" + time);
                boolean rightTime = time.getTime() > time1.getTime() && time.getTime() < time2.getTime();
                System.out.println(rightTime);
                if ((tempCount < maxCount) && (status == 2 || status == 4) && rightTime) {
                    //插入活动用户表
                    activityUser.setAttendTime(now2);
                    System.out.println(activityUser.toString());
                    boolean result1 = activityUserDao.activityUserAdd(activityUser);

                    //活动表更新
                    tempActivity.setTempCount(String.valueOf(tempCount + 1));
                    int modifyNum = activityDao.activityModify(tempActivity);
                    if (result1 && modifyNum == 1) {
                        result.setStatus(200);  //
                        result.setMsg("success");
                        result.setDataEntry("total", 1);
                    } else {
                        result.setStatus(400);  //
                        result.setMsg("数据库更新失败");
                    }
                } else {
                    result.setStatus(300);  //
                    result.setMsg("该活动人数已达上限或未到报名时间或活动未批准");
                }
            }
        } catch (Exception e) {
            result.setStatus(401);
            result.setMsg("failed");
            e.printStackTrace();
        } finally {
            System.out.println(result);
        }
        ResponseUtil.write(resp, result.get());
    }
}


